<?php

namespace App\Http\Controllers;

use App\Template;
use Illuminate\Http\Request;

class CollectController extends Controller
{
    //
    public function store(Request $request)
    {
        $this->validate($request, [
            'url' => 'required|url'
        ]);

        $data = $this->parseUrl($request->input('url'));
        Template::create($data);

        return 'ok';
    }

    private function parseUrl($url)
    {
        $map = [
            'maka' => '/maka.im/',
            'eqxiu' => '/eqxiu.com/',
        ];

        foreach ($map as $name => $site) {
            if (preg_match($site, $url)) return $this->{'store'.ucfirst($name)}($url);
        }

        throw new \Exception("can't parse the url: '$url'");
    }

    private function storeMaka($url)
    {
        preg_match('#maka.im/store/preview/(.+)#', $url, $match);

        if (!isset($match[1]) || empty($match[1])) throw new \Exception("invalid url: '$url'");

        $id = $match[1];

        $data_url = "http://api.maka.im/api/storeTemplate/{$id}?dataType=pdata";

        $html = file_get_contents($url);

        preg_match('#var STORE_TEMPLATE_INFO = (\{.+\})#', $html, $match);
        if (!isset($match[1])) throw new \Exception('network error.');
        $tmp_info = json_decode($match[1]);

        $data = json_decode(file_get_contents($data_url));

        if ($data->code != 200) throw new \Exception("invalid url: '$url'. at code: {$data->code}");

        return
            [ 'title'       => $tmp_info->title
            , 'description' => $tmp_info->content
            , 'collection'  => json_encode($data)
            , 'raw_id'      => '1_'.$id
            ];
    }

    private function storeEqxiu($url)
    {
        ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; 4399Box.560; .NET4.0C; .NET4.0E)');
        $html = file_get_contents($url);
        preg_match("#<h2 class=\"e_name\" productId = '\\d+' sourceId = '(\\d+)'[^>]+>([^<]+)</h2>#", $html, $match);
        list(, $id, $title) = $match;

        preg_match('#<div class="s_list"> <label>样例描述：</label> <span>([^<]+)</span>#', $html, $match);

        $data_url = "http://s1.eqxiu.com/eqs/page/{$id}";
        $data = file_get_contents($data_url);

        return
        [ 'title'       => $title
        , 'description' => $match[1]
        , 'collection'  => $data
        , 'raw_id'      => '2_'.$id
        ];
    }
}
